package com.atguigu.jxc.service.impl;

import com.alibaba.fastjson.JSONObject;
import com.atguigu.jxc.dao.DamageDao;
import com.atguigu.jxc.dao.UserDao;
import com.atguigu.jxc.domain.ServiceVO;
import com.atguigu.jxc.entity.DamageList;
import com.atguigu.jxc.entity.DamageListGoods;
import com.atguigu.jxc.entity.User;
import com.atguigu.jxc.service.DamageService;
import com.atguigu.jxc.util.StringUtil;
import org.apache.shiro.SecurityUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Service
public class DamageServiceImpl implements DamageService {
    @Autowired
    private DamageDao damageDao;
    @Autowired
    private UserDao userDao;

    //保存报损单
    @Override
    public ServiceVO saveDamageListGoods(DamageList damageList, String damageListGoodsStr) {

        //damageListGoodsStr: [{"goodsId":14,"goodsTypeId":8,"goodsCode":"0006","goodsName":"冰糖金桔干","goodsModel":"300g装","goodsUnit":"盒","lastPurchasingPrice":5,"price":"52","goodsNum":"22","total":1144}]
      //  DamageListGoods

        //获取当前登录的用户名
        String userName = (String) SecurityUtils.getSubject().getPrincipal();
        //根据用户名查询用户信息
        User user = userDao.findUserByName(userName);
        damageList.setUserId(user.getUserId());
        damageList.setTrueName(user.getTrueName());
        int count=0;
        List<DamageListGoods> damageListGoodsList=null;
        if(!StringUtil.isEmpty(damageListGoodsStr)){
            damageListGoodsList = JSONObject.parseArray(damageListGoodsStr, DamageListGoods.class);
        }
        //把damageList对象放在t_damage_list表中
        damageDao.saveDamageList(damageList);
        for (DamageListGoods damageListGood : damageListGoodsList) {
            damageListGood.setDamageListId(damageList.getDamageListId());
            count=damageDao.saveDamageListGoods(damageListGood);
        }
        if(count>0){
            return new ServiceVO(100,"请求成功");
        }
        return new ServiceVO(250,"请求失败");
    }

    //查询报损列表
    @Override
    public Map<String, Object> damageListGoods(String sTime, String eTime) {
        HashMap<String, Object> map = new HashMap<>();
        List<DamageList> damageList=damageDao.damageListGoods(sTime,eTime);
        User user = new User();

        for (DamageList list : damageList) {
            Integer userId = list.getUserId();
            user= userDao.getUserById(userId);
            String trueName = user.getTrueName();
            list.setTrueName(trueName);
        }
        map.put("rows",damageList);
        return map;
    }

    //查询报损单商品信息
    @Override
    public Map<String, Object> damageGoods(Integer damageListId) {
        HashMap<String, Object> map = new HashMap<>();
        List<DamageListGoods>  list=damageDao.damageGoods(damageListId);
        map.put("rows",list);
        return map;
    }
}
